/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package chatsoft.server.buz;

import ChatSoft.model.User;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

/**
 *
 * @author KID
 */
public class XmlHandle {

    User us;

    public User xmlToUser(String xmlName) {
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder domParser = factory.newDocumentBuilder();
            Document pdom = domParser.parse(xmlName);
            return domToUser(pdom);

        } catch (SAXException ex) {
            return null;
        } catch(FileNotFoundException ex)
        {
            return null;
        }
        catch (IOException ex) {
            return null;
        } catch (ParserConfigurationException ex) {
            return null;
        }
    }

    private User domToUser(Node node) {

        if (node.getNodeType() == Node.ELEMENT_NODE) {
            if (node.getNodeName().equalsIgnoreCase("user")) {
                us = new User();
            } else if ("username".equals(node.getNodeName())) {
                String name = node.getChildNodes().item(0).getNodeValue();
                us.setUserName(name);
            } else if ("password".equals(node.getNodeName())) {
                String password = node.getChildNodes().item(0).getNodeValue();
                us.setPassword(password);
            } else if ("avatar".equals(node.getNodeName())) {
                String avatar = node.getChildNodes().item(0).getNodeValue();
                us.setAvatar(avatar);
            } else if ("friend".equals(node.getNodeName())) {
                String friend = node.getChildNodes().item(0).getNodeValue();
                us.getFriendsList().add(friend);
            }

        }
        NodeList childNode = node.getChildNodes();
        int childNodeCount = childNode.getLength();
        for (int i = 0; i < childNodeCount; i++) {
            Node child = childNode.item(i);
            domToUser(child);
        }
        return us;
    }

    public void WriteUserToXML(User user) {
        try {
            System.out.println("write xml");
            DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

            // root elements
            Document doc = docBuilder.newDocument();
            Element rootElement = doc.createElement("userroot");
            doc.appendChild(rootElement);
            // ussr elements
            Element User = doc.createElement("user");
            rootElement.appendChild(User);
            Element name = doc.createElement("username");
            name.appendChild(doc.createTextNode(user.getUserName()));
            User.appendChild(name);
            Element password = doc.createElement("password");
            password.appendChild(doc.createTextNode(user.getPassword()));
            User.appendChild(password);
            Element avatar = doc.createElement("avatar");
            avatar.appendChild(doc.createTextNode(user.getAvatar()));
            User.appendChild(avatar);
            
            for (String fr : user.getFriendsList()) {
                Element friend = doc.createElement("friend");
                friend.appendChild(doc.createTextNode(fr));
                User.appendChild(friend);
                
            }
            // write the content into xml file
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            DOMSource source = new DOMSource(doc);
            StreamResult result = new StreamResult(new File("src/chatsoft/server/userplace/" + user.getUserName() + ".xml"));

            // Output to console for testing
            transformer.transform(source, result);
            System.out.println("File saved!");
        } catch (ParserConfigurationException pce) {
            System.out.println("error write xml");
            pce.printStackTrace();
        } catch (TransformerException tfe) {
            tfe.printStackTrace();
            System.out.println("error write xml");
        }
    }
}
